<template>
    <a-layout-content style="padding: 0 50px">
        <a-layout style="padding: 24px 0; background: #fff">
            <a-layout-content :style="{ padding: '0 24px', minHeight: '280px' }">
                <p>
                    <a-form layout="inline" :model="param">
                        <a-form-item>
                            <a-button type="primary" @click="add">新增</a-button>
                        </a-form-item>
                    </a-form>
                </p>
                <a-table :dataSource="templates"
                         :columns="columns"
                         :row-key="record=>record.id"
                         :pagination="pagination"
                         :loading="loading"
                         @change="handleTableChange">
                    <template #brandIds='{text,record,index}'>
                        {{jsonToString(text,'text')}}
                    </template>
                    <template #specIds='{text,record,index}'>
                        {{jsonToString(text,'text')}}
                    </template>
                    <template #customAttributeItems='{text,record,index}'>
                        {{jsonToString(text,'text')}}
                    </template>
                    <template v-slot:action="{text,record}">
                        <a-button type="primary"  @click="edit(record)">
                            编辑
                        </a-button>
                        <a-popconfirm
                                title="删除后无法恢复，确认删除?"
                                ok-text="是"
                                cancel-text="否"
                                @confirm="del(record.id)"
                        >
                            <a-button type="danger">
                                删除
                            </a-button>
                        </a-popconfirm>
                    </template>
                </a-table>
            </a-layout-content>


        </a-layout>

        <a-modal v-model:visible="modalVisible"
                 title="商品模板编辑表单"
                 :confirm-loading="modalLoading"
                 @ok="handleModalOk"
                 cancel-text="取消"
                 ok-text="确定"
        >
            <a-form :model="templateEntity" :label-col="{span:6}" :wrapper-col="wrapperCol">
                <a-form-item label="分类模板名称">
                    <a-input v-model:value="templateEntity.name" />
                </a-form-item>
                <a-form-item label="关联品牌">
                    <a-select
                            v-model:value="templateEntity.brandIds"
                            mode="multiple"
                            style="width: 100%"
                            placeholder="选择品牌..."
                            :labelInValue="true"
                    >
                        <a-select-option v-for="item in brandList"
                                         :key="item.id"
                                         :value="item.id"
                                         :label="item.name"
                        >
                            {{item.name}}
                        </a-select-option>
                    </a-select>
                </a-form-item>

                <a-form-item label="关联规格">
                    <a-select
                            v-model:value="templateEntity.specIds"
                            mode="multiple"
                            style="width: 100%"
                            placeholder="选择规格..."
                            :labelInValue="true"
                    >
                        <a-select-option v-for="item in specificationList"
                                         :key="item.id"
                                         :value="item.id"
                                         :label="item.specName"
                        >
                            {{item.specName}}
                        </a-select-option>
                    </a-select>
                </a-form-item>

                <a-form-item label="扩展属性">
                    <a-button type="primary" :size="small" @click="addTableRow">新增扩展属性</a-button>
                    <table id="tb01" width="340px" >
                        <thead>
                        <tr>
                            <td>属性名称</td>
                            <td>操作</td>
                        </tr>
                        </thead>
                        <tbody>
                        <tr v-for="pojo in templateEntity.customAttributeItems" v-bind:key="pojo.id">
                            <td><a-input v-model:value="pojo.text"/></td>
                            <td><a-button :size="small" danger block @click="deleTableRow($index)">删除</a-button></td>
                        </tr>
                        </tbody>
                    </table>
                </a-form-item>
            </a-form>
        </a-modal>

    </a-layout-content>
</template>

<script lang="ts">
    import { defineComponent, ref,onMounted } from 'vue';
    import axios from "axios";
    import {message} from "ant-design-vue"

    export default defineComponent({
        name: "admin-template",
        setup(){
            const columns= [
                {
                    title: '模板id',
                    dataIndex: 'id'
                },
                {
                    title: '分类模板名称',
                    dataIndex: 'name'
                },
                {
                    title: '关联品牌',
                    dataIndex: 'brandIds',
                    slots: {customRender: 'brandIds'}
                },
                {
                    title: '关联品牌',
                    dataIndex: 'specIds',
                    slots: {customRender: 'specIds'}
                },
                {
                    title: '扩展属性',
                    dataIndex: 'customAttributeItems',
                    slots: {customRender: 'customAttributeItems'}
                },
                {
                    title: '操作',
                    key:'action',
                    slots:{
                        customRender:'action'
                    }
                }
            ]
            const pagination = ref({
                current:1,
                pageSize:5,
                total:0
            });
            const modalVisible = ref<boolean>(false);
            const modalLoading = ref<boolean>(false);
            const loading = ref<boolean>(false);

            const templates=ref();
            const templateEntity=ref<any>({
                name:'',
                brandIds:'',
                specIds:'',
                customAttributeItems:[]
            });
            const maxTagTextLength = ref(10);
            const brandOption = ref([]);
            const brandList = ref();
            const specificationList = ref();

            const handleQuery =(params:any)=>{
                loading.value=true;
                axios.get("http://localhost:8899/mall-manager/template/getTempByPage",{
                    params:{
                        page:params.page,
                        size:params.size
                    }
                }).then((response)=>{
                    loading.value=false;
                    templates.value=response.data.list;
                    //重置分页按钮
                    pagination.value.current=params.page;
                    pagination.value.total=response.data.total;
                })
            }

            const handleModalOk=()=>{
                modalLoading.value = false;

                let template_arr:Array<any> = [];
                (templateEntity.value.brandIds as Array<any>).forEach(item=>{
                    template_arr.push({
                        id:item.option.value,
                        text:item.option.label
                    })
                });
                //转json对象（集合）为字符串
                templateEntity.value.brandIds =  JSON.stringify(template_arr);

                let spec_arr:Array<any> = [];
                (templateEntity.value.specIds as Array<any>).forEach(item=>{
                    spec_arr.push({
                        id:item.option.value,
                        text:item.option.label
                    })
                });
                //转json对象（集合）为字符串
                templateEntity.value.specIds = JSON.stringify(spec_arr);
                templateEntity.value.customAttributeItems = JSON.stringify(templateEntity.value.customAttributeItems);

                axios.post('http://localhost:8899/mall-manager/template/saveOrUpdateTemplate',templateEntity.value).then((respone)=>{
                    modalLoading.value = false;
                    if (respone.data.code=='200'){
                        modalVisible.value = false;
                        handleQuery({
                            page:pagination.value.current,
                            size:pagination.value.pageSize
                        });
                    } else {
                        message.error(respone.data.message);
                    }
                });

            };

            const handleTableChange = (pagination:any)=>{
                handleQuery({
                    page:pagination.cuechange,
                    size:pagination.size
                })
            }

            //添加新行
            const addTableRow = ()=>{
                templateEntity.value.customAttributeItems.push({});
            };

            const edit=(record:any)=>{
                console.log(record);
            }
            const add=()=>{
                modalVisible.value=true;
                templateEntity.value={customAttributeItems:[]};
            }
            const del=(id:number)=>{
                axios.delete('http://localhost:8899/mall-manager/template/deleteTemp/'+id).then(reponse=>{
                    if (reponse.data.code==200){
                        //加载最新数据
                        handleQuery({
                            page:1,
                            size:pagination.value.pageSize
                        });
                    }else {
                        message.error(reponse.data.message)
                    }
                })
            }

            //删除行
            const deleTableRow = (index:number) =>{
                templateEntity.value.customAttributeItems.splice(index,1);
            };

            const jsonToString = (jsonString:any,key:any)=>{
                let json= JSON.parse(jsonString);
                let value="";
                for(let i=0;i<json.length;i++){
                    if(i>0){
                        value+=",";
                    }
                    value +=json[i][key];
                }
                return value;
            };

            const handleBrand=()=>{
                axios.get('http://localhost:8899/mall-manager/brand/getAllBrand').then(reponse=>{
                    brandList.value=reponse.data.data;
                })
            }

            const handleSpecification=()=>{
                axios.get('http://localhost:8899/mall-manager/specification/findAllSpec').then(reponse=>{
                    specificationList.value=reponse.data.data;
                })
            }


            onMounted(()=>{
                handleQuery({
                    page:1,
                    size:pagination.value.pageSize
                });
                handleBrand();
                handleSpecification();
            });
            return{
                columns,
                pagination,
                modalVisible,
                modalLoading,
                templates,
                loading,
                brandList,
                maxTagTextLength,
                brandOption,
                specificationList,
                templateEntity,
                handleQuery,
                handleTableChange,
                handleModalOk,
                jsonToString,
                addTableRow,
                deleTableRow,
                edit,
                del,
                add,
                handleSpecification,
                handleBrand
            }
        }
    })
</script>

<style scoped>

</style>